import styles from "@pages/personal/styles/styles.module.less";
// import React from "react";
import { SlideRef } from "@shared/slide";
import React, { ChangeEvent, useEffect, useRef } from "react";
import { useUploadAvatarMutation } from "@service/user";
import Loading from "@shared/loading";
import toast from "react-hot-toast";

interface Props {
  // slide 组件实例对象, 因为当前组件将来要关闭弹窗
  // 所以当前组件要接收弹层对象实例
  slideRef: React.RefObject<SlideRef | null>;
}

export default function UpdateAvatar({ slideRef }: Props) {
  const fileRef = useRef<HTMLInputElement | null>(null);
  // 用于实现头像上传
  const [uploadAvatar, { isLoading, isError, isSuccess }] = useUploadAvatarMutation();
  const uploadAvatarHandler = (event: ChangeEvent<HTMLInputElement>) => {
    // 获取用户选择的文件列表
    const files = event.currentTarget.files;
    // 判断用户是否选择了文件
    if (files === null) return;
    if (typeof files[0] === "undefined") return;
    // 创建表单对象
    const formData = new FormData();
    // 向表单对象中添加字段
    formData.append("photo", files[0]);
    // 发送请求更新头像
    uploadAvatar(formData);
  };

  // 拍照或选择照片
  const trigger = (mark: "take" | "select") => {
    // 拍照
    if (mark === "take") {
      // user: 前置摄像头 environment: 后置摄像头
      fileRef.current?.setAttribute("capture", "user");
      // 选择照片
    } else if (mark === "select") {
      fileRef.current?.removeAttribute("capture");
    }
    // 触发点击事件
    fileRef.current?.click();
  };

  // 监听请求是否出现错误
  useEffect(() => {
    // 用户提示
    if (isError) toast.error("头像上传失败");
  }, [isError]);

  // 监听请求是否成功
  useEffect(() => {
    // 用户提示
    if (isSuccess) {
      toast.success("头像更新成功");
      // 销毁弹框
      slideRef.current?.close();
    }
  }, [isSuccess, slideRef]);

  return (
    <>
      <ul className={styles.list}>
        <li onClick={() => trigger("take")}>拍照</li>
        <li onClick={() => trigger("select")}>选择照片</li>
        <li onClick={slideRef.current?.close}>取消</li>
      </ul>
      <input
        ref={fileRef}
        type="file"
        onChange={uploadAvatarHandler}
        accept="image/png, image/gif, image/jpeg"
        style={{ display: "none" }}
      />
      {isLoading ? <Loading /> : null}
    </>

  );
}
